"""
Verify AIPPT Module Implementation
Tests all services and client implementations
"""
import sys
import os

# Add project root to path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, project_root)

from dotenv import load_dotenv

# Load environment variables from .env file in project root
env_path = os.path.join(project_root, '.env')
load_dotenv(env_path)

from src.llm.aippt_app import (
    TemplateService,
    PPTGenerationService,
    PPTManagementService,
    AIPPTAPIClient
)

print("=" * 60)
print("AIPPT Module Verification")
print("=" * 60)


# ============================================================
# Test 1: Template Service
# ============================================================
def test_template_service():
    """Test template service"""
    print("\n" + "=" * 60)
    print("TEST 1: Template Service")
    print("=" * 60)

    try:
        service = TemplateService()

        # Test 1.1: Get filter options
        print("\n1.1 Getting template filter options...")
        options = service.get_filter_options()
        print(f"Result: {'SUCCESS' if options else 'FAILED'}")
        if options and options.get('data'):
            data = options['data']
            print(f"  - Theme colors: {len(data.get('themeColor', []))}")
            print(f"  - Categories: {len(data.get('category', []))}")
            print(f"  - Styles: {len(data.get('style', []))}")

        # Test 1.2: Get random templates
        print("\n1.2 Getting random templates...")
        templates = service.get_random_templates(count=3)
        print(f"Result: {'SUCCESS' if templates else 'FAILED'}")
        if templates:
            print(f"  - Retrieved {len(templates)} templates")
            if templates:
                print(f"  - First template ID: {templates[0].get('id')}")

        return True

    except Exception as e:
        print(f"FAILED: {str(e)}")
        return False


# ============================================================
# Test 2: PPT Generation Service
# ============================================================
def test_ppt_generation_service():
    """Test PPT generation service"""
    print("\n" + "=" * 60)
    print("TEST 2: PPT Generation Service")
    print("=" * 60)

    try:
        service = PPTGenerationService()

        # Test 2.1: Get generation options
        print("\n2.1 Getting generation options...")
        options = service.get_generation_options()
        print(f"Result: {'SUCCESS' if options else 'FAILED'}")
        if options and options.get('data'):
            data = options['data']
            print(f"  - Audiences: {len(data.get('audience', []))}")
            print(f"  - Languages: {len(data.get('lang', []))}")
            print(f"  - Page counts: {len(data.get('pageCount', []))}")

        # Test 2.2: Create task
        print("\n2.2 Creating PPT generation task...")
        task_id = service.create_task_from_text(
            content="Artificial Intelligence in Education",
            task_type=1
        )
        print(f"Result: {'SUCCESS' if task_id else 'FAILED'}")
        if task_id:
            print(f"  - Task ID: {task_id}")

        # Note: We don't test content generation to avoid consuming credits
        print("\n2.3 Content generation - SKIPPED (to avoid credit consumption)")

        return True

    except Exception as e:
        print(f"FAILED: {str(e)}")
        return False


# ============================================================
# Test 3: PPT Management Service
# ============================================================
def test_ppt_management_service():
    """Test PPT management service"""
    print("\n" + "=" * 60)
    print("TEST 3: PPT Management Service")
    print("=" * 60)

    try:
        service = PPTManagementService()

        # Test 3.1: List user PPTs
        print("\n3.1 Listing user PPTs...")
        ppts = service.list_user_ppts(current=1, size=5)
        print(f"Result: {'SUCCESS' if ppts else 'FAILED'}")
        if ppts and ppts.get('data'):
            records = ppts['data'].get('records', [])
            print(f"  - Total PPTs: {ppts['data'].get('total', 0)}")
            print(f"  - Retrieved: {len(records)}")

        return True

    except Exception as e:
        print(f"FAILED: {str(e)}")
        return False


# ============================================================
# Test 4: API Client Direct Tests
# ============================================================
def test_api_client():
    """Test API client directly"""
    print("\n" + "=" * 60)
    print("TEST 4: API Client Direct Tests")
    print("=" * 60)

    try:
        client = AIPPTAPIClient()

        # Test 4.1: Configuration validation
        print("\n4.1 Validating configuration...")
        client.config.validate_config()
        print("Result: SUCCESS")
        print(f"  - Base URL: {client.config.BASE_URL}")
        print(f"  - Token: {client.config.TOKEN[:10]}...")

        return True

    except Exception as e:
        print(f"FAILED: {str(e)}")
        return False


# ============================================================
# Main Execution
# ============================================================
if __name__ == "__main__":
    print("\nStarting verification tests...\n")

    results = {
        'template_service': test_template_service(),
        'ppt_generation_service': test_ppt_generation_service(),
        'ppt_management_service': test_ppt_management_service(),
        'api_client': test_api_client()
    }

    # Summary
    print("\n\n" + "=" * 60)
    print("VERIFICATION SUMMARY")
    print("=" * 60)
    for test_name, result in results.items():
        status = "PASSED" if result else "FAILED"
        print(f"{test_name:30s} {status}")
    print("=" * 60)

    # Overall result
    all_passed = all(results.values())
    if all_passed:
        print("\nAll tests PASSED!")
        sys.exit(0)
    else:
        print("\nSome tests FAILED!")
        sys.exit(1)
